package com.itheima.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        //1. 获取访问资源路径
        String uri = request.getRequestURI();
        //System.out.println(uri);

        // 无需判断是否登录的资源, 直接放行
        if (uri.contains("/login.jsp")
                || uri.contains("/index.jsp")
                || uri.contains("/css")
                || uri.contains("/js")
                || uri.contains("/fonts")
                || uri.contains("/checkCode")
                || uri.contains("/loginServlet")) {
            // 放行
            chain.doFilter(req, resp);
            return;
        }

        //2.判断用户是否登录, 控制是否可以访问资源
        Object user = request.getSession().getAttribute("user");

        if (user == null) {
            request.setAttribute("msg", "您尚未登录,请登录后再试!!!");
            request.getRequestDispatcher("/login.jsp").forward(request, resp);
            return;
        }
        // 登录了, 放行
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
